package com.zHan.system.filter;

import com.alibaba.fastjson.JSON;
import com.zHan.common.result.Result;
import com.zHan.common.result.ResultCodeEnum;
import com.zHan.common.utils.JwtUtil;
import com.zHan.common.utils.ResponseUtil;
import com.zHan.common.utils.ThreadLocalUtil;
import com.zHan.model.constant.RedisConstant;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 认证解析token过滤器
 * </p>
 */

public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private StringRedisTemplate stringRedisTemplate;

    public TokenAuthenticationFilter(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 登录接口的配置工作
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain)
            throws IOException, ServletException {
        logger.info("uri:" + request.getRequestURI());
        //如果是登录接口，直接放行
        if ("/admin/system/index/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
        }
    }

    /**
     * 用户名密码的授权
     *
     * @param request
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader("token");
        logger.info("token:" + token);
        if (!StringUtils.isEmpty(token)) {
            // 根据token获取用户名
            Map<String, String> tokenMap = JwtUtil.getToken(token);
            String username = tokenMap.get("username");

            // 将解析的jwt令牌存入ThreadLocal
            ThreadLocalUtil.set(tokenMap);

            // 从redis中获取token
            String tokenKey = RedisConstant.TOKEN_KEY + token;
            String redisToken = stringRedisTemplate.opsForValue().get(tokenKey);
            if (redisToken == null) {
                throw new AccessDeniedException("token不存在，请登录");
            }

            if (!StringUtils.isEmpty(username)) {
                String authKey = RedisConstant.AUTHORITY_KEY + username;
                String authoritiesString = stringRedisTemplate.opsForValue().get(authKey);
                List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (Map map : mapList) {
                    authorities.add(new SimpleGrantedAuthority((String) map.get("authority")));
                }

                return new UsernamePasswordAuthenticationToken(username, null,
                        authorities);
            }
        }
        return null;
    }
}